<?php
/**
 * Created by PhpStorm.
 * User: Kevin
 * Date: 2019/6/18
 * Time: 18:25
 */
namespace app\admin\controller;

use think\Controller;
use think\Db;
class Sharenew extends Controller{
    // 定义配置项
    private $config=array(
        'NOTIFY_URL'         => 'http://csdl.jintianjifen.cn/api/Dxhuidiao/huidiao1', // 接收支付状态的连接
        'NOTIFY_URLFWS'         => 'http://csdl.jintianjifen.cn/api/Dxhuidiao/huidiao2', // 接收支付状态的连接
    );
    private static $PRIVATE_KEY ='-----BEGIN PRIVATE KEY-----
MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAILcG3bJ2l1/lU5K
TN6/wCQv0mnj1d19ffOK3g92Ip9p8IuqTl4oTC/67ciJ31O21Ru8gCg8s0CCkS2o
zyNtFK2ngM0ChFqab29SKBc+xbGBhaZ2+YIhSpVbjMVfA7ffRQR85jgt4gpcDbtv
FXj4KlEiHbfumVyqSO5KoPY0tAt1AgMBAAECgYAqZQTAx0RnZh4I7ylYQOcO0i9o
/tcamr1jWWn3uF4fJ0M2/EXHW2bTZIgEoCYqCOGhyr/6STAJhkNid34kDALWg248
2BzVuP9dnt6nPR0hJTEkGoOO24k+yQLX2rtoYoEq7cBtZZMlxGDbKTzwb6MtlZ8/
g0fY2h+Dhi6EO12YAQJBAPiFkib1UIeEUP2BdoLxsL+bD2oXUVPELrGUNieC+7ZE
8kRTeMT3AcQW08R92esim0n6FGu2Aj5F3smAnzJNgSECQQCGzCeur3mzv9NOtyUg
F4tvtNjjHwoJngFbDGtdFQzTCY4WGOIP+iMgFWQrK3izqpCywGr00BuzSkZquTJt
1TvVAkBVXBt9Ahls0oe26va3tygMR8gdmnC2otWe7NdE7vph+oBz82+xx1116plG
DiwBVVudJyZIcLWIihshfuovLuvBAkBq3a3UIs/Ufo7SyAXJ1IC6FeEg5rm5eCfQ
/B6eFBMvuFKKGD4YtpFkXTElvHgb0GyZGk1xOw/K62a6M4rUYonlAkEA6FYBIdj5
zEkr6YYsShx15frEhf8yAjegJgrvZUPWHDGWs6lQmveDuIu3rkKOSgfVssghiABK
6NxE8U/eIKoPOA==
-----END PRIVATE KEY-----';
    private static $PUBLIC_KEY  ='-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCiYHZyQ6JGGFJiM3yQCKquxVs9
KCIBfnooLjiMg9ZLsnMk0ChRWV1bKhzJuMVdCdsfVxEhn0D2ydXDwxWhQA6PMCVg
G77WSifodUSwKp/Rcvj4aeDO1gUbHOYg7HseEV9/zIUrhXCZRpGPfQyPjfZ7yI9f
dI1GcTQ6dXl5tBc7zQIDAQAB
-----END PUBLIC KEY-----';
    public function index(){
        return $this->fetch ('share/index');
    }

    public function invite(){
        return $this->fetch ('share/invite');
    }

    public function home(){
        return $this->fetch ('share/home');
    }

    public function treasure(){
        return $this->fetch ('share/treasure');
    }

    public function posts(){
        return $this->fetch ('share/post');
    }
    public function register(){
        if(!isset($_REQUEST['shop_id']) || !$_REQUEST['shop_id']){
            return $this->fetch('share/register');
        }
        $shop_id = $_REQUEST['shop_id'];
        if(!isset($_REQUEST['code'])){
            echo '不合法二维码';
            exit();
        }else{
            $code = $_REQUEST['code'];
        }
        $data = [];
        if($code){
            $data = Db::table('up_u_user')
                ->where('user_invite_code', $code)
                ->find();
            if(empty($data)){
                echo '此码已不可用!';
                exit();
            }
            if($data['user_status'] != 1){
                echo '此码已暂停收款';
                exit();
            }
        }
        session('invite_code',$code);
        session('shop_id',$shop_id);
        $this->assign('data',$data);
        if(strpos($_SERVER['HTTP_USER_AGENT'],'MicroMessenger')!==false){
            session('session_type',2);
            if(!session('?openid22')){
                $authurl = $this->config['AUTH_URL'];
                $appid = config('wechat')['appid'];
                echo "<script> location.href='https://open.weixin.qq.com/connect/oauth2/authorize?appid={$appid}&redirect_uri={$authurl}&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect'; </script>";
                exit;
            }
            $this->assign('paytype',2);
            $user = Db::table('up_u_user')
                ->where('user_m_h5_wx', session('openid22'))
                ->find();
            if($user){ //存在就去主页
                $shopData = $this->recordRule($shop_id);

                $this->assign($shopData);
                $this->assign('user',$user);
                $this->assign('user222',session('invite_code'));
                return $this->fetch('shareh/index');
            }else{ //不存在就去绑定页
                return $this->fetch('shareh/bangding');
            }

        }elseif (strpos($_SERVER['HTTP_USER_AGENT'],'AlipayClient')!==false){
            session('session_type',1);
            if(!session('?openid11')){
                echo "<script> location.href='https://openauth.alipay.com/oauth2/publicAppAuthorize.htm?app_id=2019052065205188&scope=auth_base&redirect_uri=http://csdl.jintianjifen.cn/admin/Authali/getuser'; </script>";
                exit;
            }
            $this->assign('paytype',1);
            $user = Db::table('up_u_user')
                ->where('user_m_h5_zfb', session('openid11'))
                ->find();
            if($user){ //存在就去主页
                $shopData = $this->recordRule($shop_id);

                $this->assign($shopData);
                $this->assign('user',$user);
                return $this->fetch('shareh/index');
            }else{ //不存在就去绑定页
                return $this->fetch('shareh/bangding');
            }
        }else{
            echo "请使用微信扫码或者支付宝扫码！";
            exit();
        }
    }
    /**
     * 绑定
     * @return mixed|\think\response\Json
     */
    public function bangding(){
        extract(input());
        if(!isset($phone) || !isset($code)){
            return json(['status'=>100,'msg'=>'参数错误']);
        }
        if(!preg_match("/^1[3456789]\d{9}$/", $phone)) {
            return json(['status'=>100,'msg'=>'请填写正确的手机号码']);
        }
        if($code == ''){
            return json(['status'=>100,'msg'=>'请填写验证码']);
        }
        $phone_code = Db::name('phonecode')->where(['phone'=>$phone,'status'=>0,'type'=>1])->find();
        if(empty($phone_code)){
            return json(['status'=>100,'msg'=>'请先发送验证码']);
        }
        $diff = time() - $phone_code['time'];
        if($diff >= 30*60){
            return json(['status'=>100,'msg'=>'验证码已失效']);
        }
        if($code != $phone_code['code']){
            return json(['status'=>100,'msg'=>'验证码输入错误']);
        }
        $user = Db::table('up_u_user')->where('user_phone',$phone)->find();
        $invite_code = session('invite_code');
        if(session('session_type') == 1){
            $fieldMww = 'user_m_h5_zfb';
            $valueMww = session('openid11');
        }else{
            $fieldMww = 'user_m_h5_wx';
            $valueMww = session('openid22');
        }
        if($user){
            if($user[$fieldMww]){
                return json(['status'=>100,'msg'=>'此手机号已被绑定']);
            }else{
                $update = [
                    $fieldMww => $valueMww
                ];
                $res = Db::table('up_u_user')->where('user_phone',$phone)->update($update);
                if($res){
                    return json(['status'=>200,'msg'=>'绑定成功！','url'=>'/admin/Share/register?code=' . $invite_code . '&shop_id=' . session('shop_id')]);
                }else{
                    return json(['status'=>100,'msg'=>'绑定失败，请刷新重试！']);
                }
            }
        }else{
            Db::startTrans ();
            try{
                $token = md5(date('YmdHis') . rand(100000,999999));
                $user_id = Db::name("u_user")->insertGetId([
                    'user_username'=>$phone,
                    'user_phone'=>$phone,
                    'user_time'=>date("Y-m-d H:i:s"),
                    'user_token'=>$token,
                    $fieldMww => $valueMww
                ]);
                if($invite_code){
                    $give = Db::name('jifen_conf')->where('conf_id',16)->value('conf_rate');
                    $form = Db::name('u_user')->where('user_invite_code',$invite_code)->find();
                    if(empty($form)){
                        return json(['status'=>100,'msg'=>'邀请码输入错误']);
                    }
                    if($form['user_area'] == ''){
                        Db::name('u_user')->where(['user_id'=>$form['user_id']])->update (['user_province'=>1055,'user_city'=>1065,'user_area'=>1134]);
                        $form['user_area'] = 1134;
                    }else{
                        // 邀请人注册区没有代理
                        $is_qu = DB::name('admin')->where(['area'=>$form['user_area']])->find();
                        if (empty($is_qu)) {
                            $form['user_area'] = 1134;
                        }
                    }
                    $apithis = new \app\api\controller\Base();

                    //如果邀请方是合伙人另外奖励
                    $is_partner = DB::name('partner')
                        ->where(['par_user_id'=>$form['user_id'],'par_cancel'=>0])
                        ->find();
                    if (!empty($is_partner)) {
                        // 添加推荐人
                        DB::name('u_user')->where(['user_id'=>$user_id])->update(['user_recommend'=>$form['user_id']]);
                        // 该级别合伙人推荐粉丝奖励有效时间
                        $invite_days = DB::name('partner_class')
                            ->where(['class_id'=>$is_partner['par_class_id']])
                            ->value('class_fans_days');
                        // 邀请粉丝每天不能超过100位，超过没有奖励
                        $fans_count = DB::name('u_user')
                            ->where(['user_recommend'=>$form['user_id']])
                            ->whereTime('user_time','today')
                            ->count();
                        if ($fans_count < 100) {
                            if (time() < (strtotime($is_partner['par_add_time'])+3600*24*$invite_days)) {
                                // 合伙人一段时间内邀请粉丝积分奖励
                                $give_jifen = DB::name('partner_class')
                                    ->where(['class_id'=>$is_partner['par_class_id']])
                                    ->value('class_fans_jifen_reg');
                                // 合伙人邀请粉丝获得的奖励
                                $apithis->par_fans($user_id,3,1,$user_id);
                                // 记录获得积分
                                // DB::name('jifen_consume')->insert(['consume_content'=>'合伙人邀请好友注册获得'.$give_jifen.'积分','consume_user_id'=>$form['user_id'],'consume_add_time'=>date('Y-m-d H:i:s')]);
                                // // 添加提示
                                // Db::name('notice')->insert (['n_to'=>1,'n_title'=>'合伙人邀请好友','n_content'=>'邀请好友注册获得'.$give_jifen.'积分','n_images'=>'','n_type'=>3,'n_user_id'=>$form['user_id'],'n_read'=>1,'n_delete'=>1,'n_time'=>date('Y-m-d H:i:s'),'n_where_id'=>'']);
                                // $this->jpushUser(1,$form['user_id'],'合伙人邀请好友注册获得'.$give_jifen.'积分',json([]));
                            }else{
                                // 合伙人邀请粉丝获得的奖励
                                $apithis->par_fans($user_id,3,1,$user_id);
                            }
                        }else{
                            // 添加提示
                            Db::name('notice')->insert (['n_to'=>1,'n_title'=>'合伙人邀请好友','n_content'=>'当日邀请好友已达上限','n_images'=>'','n_type'=>3,'n_user_id'=>$form['user_id'],'n_read'=>1,'n_delete'=>1,'n_time'=>date('Y-m-d H:i:s'),'n_where_id'=>'']);
                            try {
                                $apithis->jpushUser(1,$form['user_id'],'当日邀请好友已达上限',json([]));
                            } catch (\Exception $e) {}
                        }
                    }else{
                        Db::name('admin')->where('area',$form['user_area'])->setDec('integral',$give);
                        $apithis->jifenFlow($give,$form['user_area'],$form['user_id'],'register');

                        Db::name('jifen_consume')->insert(['consume_content'=>'邀请好友获得'.$give.'积分','consume_user_id'=>$form['user_id'],'consume_add_time'=>date('Y-m-d H:i:s')]);

                        Db::name('notice')->insert (['n_to'=>1,'n_title'=>'邀请好友','n_content'=>'邀请好友获得'.$give.'积分','n_images'=>'','n_type'=>3,'n_user_id'=>$form['user_id'],'n_read'=>1,'n_delete'=>1,'n_time'=>date('Y-m-d H:i:s'),'n_where_id'=>'']);
                        try {
                            $apithis->jpushUser(1,$form['user_id'],'邀请好友获得'.$give.'积分',json([]));
                        } catch (\Exception $e) {}
                    }
                    // 邀请的注册直接成为好友
                    $focus = Db::name('user_fellow')->where(['fellow_user_id'=>$user_id,'fellow_star_user_id'=>$form['user_id']])->find();
                    if(!empty($focus)){
                        return json(['status'=>100,'msg'=>'已关注该好友']);
                    }
                    $time = date('Y-m-d H:i:s');
                    $param = [
                        [
                            'fellow_user_id'=>$user_id,
                            'fellow_star_user_id'=>$form['user_id'],
                            'fellow_add_time'=>$time
                        ],
                        [
                            'fellow_user_id'=>$form['user_id'],
                            'fellow_star_user_id'=>$user_id,
                            'fellow_add_time'=>$time
                        ]
                    ];
                    $res = Db::name('user_fellow')->insertAll ($param);
                    if($res){
                        Db::name('u_user')->where('user_id',$form['user_id'])->setInc('user_fans');
                        Db::name('u_user')->where('user_id',$user_id)->setInc('user_attention');
                    }
                }
                Db::name('phonecode')->where('phone',$phone)->setField ('status',1);
                Db::commit ();
                return json(['status'=>200,'msg'=>'成功','user_id'=>$user_id,'url'=>'/admin/Share/register?code=' . $invite_code . '&shop_id=' . session('shop_id')]);
            }catch (\Exception $e){
                Db::rollback ();
                return json(['status'=>100,'msg'=>'注册失败，请刷新重试！']);
            }
        }
    }
    public function inputpass()
    {
        return view('shareh/inputPassword');
    }
    public function setpass()
    {
        if(session('session_type') == 1){
            $fieldMww = 'user_m_h5_zfb';
            $valueMww = session('openid11');
        }else{
            $fieldMww = 'user_m_h5_wx';
            $valueMww = session('openid22');
        }
        $user = Db::name('u_user')->where($fieldMww,$valueMww)
            ->field('user_id,user_phone')->find();
        if(!$user){
            echo '请刷新重试！';
            exit();
        }else{
            $user_phone = $user['user_phone'];
            $this->assign('user_phone2',$user_phone);
            $user_phone = substr($user_phone,0,4) . '****' . substr($user_phone,7,4);
            $this->assign('user_phone',$user_phone);
            $this->assign('user_id',$user['user_id']);
            return $this->fetch ('shareh/setPass');
        }
    }
    public function QRcodePayH5(){
        extract (input());
        if(session('session_type') == 1){
            $fieldMww = 'user_m_h5_zfb';
            $valueMww = session('openid11');
        }else{
            $fieldMww = 'user_m_h5_wx';
            $valueMww = session('openid22');
        }
        $shop_id = session('shop_id');
        $user_id = Db::name('u_user')->where($fieldMww,$valueMww)->value('user_id');
        $shop = Db::name('shop')->where(['shop_id'=>$shop_id])->find();
        if(!$user_id || $type == ''){
            return json(['status'=>100,'msg'=>'参数错误，请刷新页面']);
        }
        if(!$shop_id || empty($shop)){
            if($type == 1) return json(['status'=>100,'msg'=>'收款码错误']);
            return json(['status'=>100,'msg'=>'收款码错误']);
        }
        if($type == 2){
            if((int)$integral <= 0) return json(['status'=>100,'msg'=>'积分输入错误']);
//            if(md5($passwordStr) != $payPass) return json(['status'=>1000,'msg'=>'密码错误！']);
        }
        if($type == 1){
            if (preg_match('/\.\d{3,}/', $money)) {
                return json(['status'=>100,'msg'=>'小数点后不能超过两位']);
            }
            $intMoney = $money*100;
            if($intMoney <= 0){
                return json(['status'=>100,'msg'=>'金额错误']);
            }
            $intMoneyOld = $money*100;
            $payment_type = session('session_type');
        }
        $uid = '';
        $uname = '';
        $title = '';
        $image = '';
        $real_pay = '';
        $all_pay = $money;
        $red_give = '';
        Db::startTrans ();
        try{
            $apithis = new \app\api\controller\Base();
            $order = $apithis->getOrderNumber ();
            $param = [
                'record_number'=>$order,
                'record_user_id'=>$user_id,
                'record_shop_id'=>$shop_id,
                'record_type'=>$type,
                'record_payment_type'=>$payment_type,
                'record_status'=>1,
                'record_jifen'=>$integral,
                'record_money'=>$money,
                'record_remark'=>$remark,
                'record_add_time'=>date("Y-m-d H:i:s"),
                'record_give_jifen'=>0,
                'record_lose_time'=>date("Y-m-d H:i:s",strtotime ("+15 minutes"))
            ];
            if($type == 1 && $money != ''){
                $param['record_give_jifen'] = $record_give_jifen;
//                $conf_rate = Db::name('jifen_conf')->where('conf_id',1)->value ('conf_rate');
//                $shop_ratio = DB::name('shop')->where('shop_id',$shop_id)->value('shop_ratio');
//                if (!empty($shop_ratio)) {
//                    $ratio = (10-$shop_ratio)/10;
//                    $param['record_give_jifen'] = round(($money*$ratio)/$conf_rate,0);
//                }else{
//                    $rule = Db::name('record_rule')->where(['rule_shop_id'=>$shop_id])->order("rule_cash DESC")->select ();
//                    if(!empty($rule)){
//                        $ruleForCash = array_column ($rule,'rule_cash');
//                        $ruleForIntegral = array_column ($rule,'rule_jifen');
//                        foreach($ruleForCash as $key=>$vo){
//                            if($money >= $vo){
//                                $param['record_give_jifen'] = $ruleForIntegral[$key];
//                                break;
//                            }
//                        }
//                    }
//                }
            }
            $give_jifen = $param['record_give_jifen'];
            $record_id = Db::name('record')->insertGetId ($param);
            if($type == 1){
//                if($param['record_give_jifen'] > 0){
//                    $stay = Db::name('record')->where(['record_id'=>['neq',$record_id],'record_type'=>1,'record_status'=>1,'record_shop_id'=>$shop_id])->sum ('record_give_jifen');
//                    if($param['record_give_jifen'] > $shop['shop_integral'] - $stay){
//                        try{
//                            $apithis->jpushShop (1,$shop_id,'您的店铺积分不足',json([]));
//                        }catch (\Exception $e){
//                        }
//                        Db::name('notice')->insert (['n_to'=>2,'n_title'=>'积分提醒','n_content'=>'您的店铺积分不足','n_images'=>'','n_type'=>1,'n_user_id'=>$shop_id,'n_read'=>',0,','n_delete'=>',0,','n_time'=>date('Y-m-d H:i:s')]);//消息
//                        if($type == 1) return 2;
//                        return json(['status'=>100,'msg'=>'商家积分不足']);
//                    }
//                }
                //-----------------------------算红包start 暂时关闭，开的时候直接打开即可--------------------------------------
                if($shop['shop_qu_id'] && $payment_type == 2){
                    //1、先纠正一下
                    $time = time();
                    $one_hour_ago = date("Y-m-d H:i:s", ($time - 300));
                    Db::name('m_red_user')
                        ->where('ru_user_id','>',0)
                        ->where('ru_status',1)
                        ->where('ru_get_time','<=',$one_hour_ago)
                        ->setField('ru_user_id',0);
                    //2、找一个红包并赋值(先筛除一天一区领一个，且如果标中未支付，则还是这个)
                    $where = [
                        'red_user_id' => ['>',0]
                    ];
                    $whereNo = Db::name('m_red_user')
                        ->where('ru_user_id',$user_id)
                        ->where('ru_status',2)
                        ->whereTime('ru_get_time','today')
                        ->group('ru_red_id')
                        ->column('ru_red_id');
                    if($whereNo){
                        $whereRed = Db::name('m_red')
                            ->where('red_user_area',$shop['shop_qu_id'])
                            ->where('red_status',2)
                            ->where('red_id','in',$whereNo)
                            ->column('red_user_id');
                        if($whereRed){
                            $where = [
                                'red_user_id' => ['not in',$whereRed]
                            ];
                        }
                    }
                    $redData = Db::name('m_red r')
                        ->join('m_red_user ru','r.red_id = ru.ru_red_id','left')
                        ->where(['red_status' => 2 ,'ru_user_id' => $user_id,'red_user_area' => $shop['shop_qu_id']])
                        ->where('ru_status',1)
                        ->where($where)
                        ->where('ru_money','<',$money)
                        ->find();
                    if(!$redData){
                        $redData = Db::name('m_red r')
                            ->join('m_red_user ru','r.red_id = ru.ru_red_id','left')
                            ->where(['red_status' => 2 ,'ru_user_id' => 0,'red_user_area' => $shop['shop_qu_id']])
                            ->where('ru_money','<',$money)
                            ->where($where)
                            ->order('red_add_time desc')
                            ->find();
                    }
                    if($redData){
                        $hehuoData = Db::name('u_user')
                            ->where(['user_id' => $redData['red_user_id']])
                            ->field('user_username,user_phone,user_m_name')
                            ->find();
                        if($hehuoData['user_username'] == $hehuoData['user_phone']){
                            $hehuoData['user_username'] = substr($hehuoData['user_username'],0,3) . '****' . substr($hehuoData['user_username'],7,4);
                        }
                        $uid = $redData['red_user_id'];
                        $uname = $hehuoData['user_m_name'] ?: $hehuoData['user_username'];
                        $title = $redData['red_title'];
                        $image = $redData['red_image'];
                        $real_pay = $money - $redData['ru_money'];
                        $red_give = $redData['ru_money'];
                        //3、改一下当前红包的相关值
                        Db::name('m_red_user')
                            ->where('ru_id',$redData['ru_id'])
                            ->update([
                                'ru_user_id' => $user_id,
                                'ru_get_time' => date('Y-m-d H:i:s')
                            ]);
                        //4、用户实际应该付的款
                        $moneyOld = $money - $redData['ru_money'];
                        $intMoneyOld = $moneyOld*100;
                        if($intMoneyOld <= 0){
                            Db::rollback ();
                            return json(['status'=>100,'msg'=>'金额错误']);
                        }
                        Db::name('record')->where('record_id',$record_id)
                            ->setField('record_ru_id',$redData['ru_id']);
                    }
                }
                //-----------------------------算红包 end--------------------------------------
                $weixinpay_config=$this->config;
                $config=array(
                    'goodsInfo'=>'扫码支付',
                    'institutionCode'=>'3178036418683176',
                    'merchantNo'=>'3178036418683176',
                    'notifyUrl'=>$weixinpay_config['NOTIFY_URL'],
                    'operator'=>'全天数据管理有限公司',
                    'outTradeNo'=>$order,
                    'requestDate'=>date('Y-m-d H:i:s'),
                    'subject'=>'扫码支付',
                    'timeOut'=>'300',
                    'tradeAmt'=>$intMoney,
                    'tradeType'=>'ALIPAY'
                );
                if($payment_type == 2) $config['tradeType'] = 'TENPAY';
                //---------------------------------二级商户---------------------------------------
                $shop_copy = Db::name('shop_copy')
                    ->where('sc_dx_mch_status',2)
                    ->where('sc_shop_id',$shop_id)
                    ->field('sc_dx_mch_id')->find();
                if($shop_copy && $shop_copy['sc_dx_mch_id']){
                    //小票信息
                    $xiaopiao = ['uid' .'='. $uid,'uname' .'='. $uname,'title' .'='. $title,'image' .'='. urlencode($image),'real_pay' .'='. $real_pay,'red_give' .'='. $red_give,'all_pay' .'='. $all_pay,'give_jifen' .'='. $give_jifen];
                    $addUpdate = [
                        'record_fws' => 2,
                        'record_sch_id' => $shop_copy['sc_dx_mch_id'],
                        'record_xiaopiao' => implode('&',$xiaopiao)
                    ];
//                        $add_res = $this->addFen($shop_copy['sc_dx_mch_id']);
//                        if($add_res['status'] != 200){
//                            return 3;
//                        }
                    if($give_jifen > 0){
                        $rate = Db::name('jifen_conf')->where('conf_id',1)->value ('conf_rate');
                        $less = $give_jifen * $rate * 100;
                        $fen_data = [
                            [
                                'merchantNo' => '3178036418683176',
                                'amount' => $less,
                                'memo' => '',
                            ],[
                                'merchantNo' => $shop_copy['sc_dx_mch_id'],
                                'amount' => $intMoney - $less,
                                'memo' => '',
                            ]
                        ];
                        $config['ledgerAccount'] = $fen_data;
                    }else{
                        $fenmoney = round($money * 0.0038,2) * 100;
                        if($fenmoney > 0){
                            $fen_data = [
                                [
                                    'merchantNo' => '3178036418683176',
                                    'amount' => $fenmoney,
                                    'memo' => '',
                                ],[
                                    'merchantNo' => $shop_copy['sc_dx_mch_id'],
                                    'amount' => $intMoney - $fenmoney,
                                    'memo' => '',
                                ]
                            ];
                        }else{
                            $fen_data = [
                                [
                                    'merchantNo' => $shop_copy['sc_dx_mch_id'],
                                    'amount' => $intMoney,
                                    'memo' => '',
                                ]
                            ];
                            if($intMoney > 1){
                                $fen_data = [
                                    [
                                        'merchantNo' => $shop_copy['sc_dx_mch_id'],
                                        'amount' => $intMoney - 1,
                                        'memo' => '',
                                    ],[
                                        'merchantNo' => '3178036418683176',
                                        'amount' => 1,
                                        'memo' => '',
                                    ]
                                ];
                            }
                        }
                        $config['ledgerAccount'] = $fen_data;
                    }
                    Db::name('record')->where(['record_id'=>$record_id])->update($addUpdate);
                    $config['notifyUrl'] = $weixinpay_config['NOTIFY_URLFWS'];
                }
                $respont = $this->WeChatPayReady($config);
                if($respont['status'] == 200){
                    Db::commit ();
                    return json(['status'=>200,'msg'=>$respont['msg'],'uid' => $uid,'uname' => $uname,'title' => $title,'image' => urlencode($image),'real_pay' => $real_pay,'red_give' => $red_give,'all_pay' => $all_pay,'give_jifen' => $give_jifen]);
                }else{
                    return json($respont);
                }
            }else{
                $back = $apithis->consume($user_id,$integral,$shop_id);
                $rate = Db::name('jifen_conf')->where('conf_id',2)->value ('conf_rate');
                if($back['status'] == 100){
                    return json($back);
                }else{
                    Db::name('jifen_consume')->insert (['consume_content'=>'扫码支付给“'.$shop['shop_name'].'”'.$integral.'积分','consume_user_id'=>$user_id,'consume_add_time'=>date("Y-m-d H:i:s")]);
                    Db::name('record')->where(['record_id'=>$record_id])->update(['record_status'=>2,'record_pay_time'=>date("Y-m-d H:i:s"),'record_shop_balance'=>$shop['shop_balance']+$realInputMoney,'record_money'=>$realInputMoney]);
                    Db::name('shop')->where('shop_id',$shop_id)->setInc ('shop_balance',$realInputMoney);
                    Db::name('shop')->where('shop_id',$shop_id)->setInc('shop_all_balance',$realInputMoney);
                    try{
                        $yuan = $realInputMoney;
                        $apithis->sayMyName($shop_id,$yuan,0,$order,2);
                        $apithis->jpushShop(1,$shop_id,"收款{$integral}积分",['type2' => 1024,'msg' => "积分买单到账{$yuan}元"]);
                    }catch (\Exception $e){
                    }
                    Db::commit ();
                    return json(['status'=>200,'msg'=>'支付成功']);
                }
            }
        }catch (\Exception $e){
            Db::rollback ();
            return json(['status'=>100,'msg'=>"支付失败"]);
        }
    }
    public function fen2(){
//        $res = Db::name('notice')->insert ([
//            'n_to'=>2,
//            'n_title'=>'资金异常纠正通知',
//            'n_content'=>'因切换电信进件通道，资金监测异常，现已恢复，有疑问联系服务商',
//            'n_images'=>'',
//            'n_type'=>1,
//            'n_user_id'=>853,
//            'n_read'=>1,
//            'n_delete'=>1,
//            'n_time'=>date('Y-m-d H:i:s')
//        ]);
//        dump($res);die;
//        $a = Db::name('order')
//            ->where('o_shop_id',853)
//            ->where('o_type','in','3,5')
//            ->where('o_add_time','>','2022-02-17 09:00:00')
//            ->field('o_money,o_type,o_id')
//            ->order('o_type')
//            ->select();
//        $b = Db::name('order')
//            ->where('o_shop_id',853)
//            ->where('o_type',5)
//            ->where('o_add_time','>','2022-02-17 09:00:00')
//            ->column('o_id');
//        dump($a);
//        dump($b);die;
//        unset($b[0]);
////        unset($b[6]);
//        Db::name('order')->where('o_id','in',$b)->delete();
//        dump($b);die;
//        $config=array(
//            'goodsInfo'=>'扫码支付',
//            'institutionCode'=>'3178036418683176',
//            'merchantNo'=>'3178036418683176',
//            'notifyUrl'=>'http://csdl.jintianjifen.cn/api/Dxhuidiao/huidiao1',
//            'operator'=>'全天数据管理有限公司',
//            'outTradeNo'=>'order' . time(),
//            'requestDate'=>date('Y-m-d H:i:s'),
//            'subject'=>'扫码支付',
//            'timeOut'=>'300',
//            'tradeAmt'=>50,
////            'tradeType'=>'ALIPAY'
//            'tradeType'=>'TENPAY'
//        );
//        $fen_data = [
//            [
//                'merchantNo' => '3178036418683176',
//                'amount' => 1,
//                'memo' => '',
//            ],
//            [
//                'merchantNo' => '3178000797302214',
//                'amount' => 49,
//                'memo' => '',
//            ]
//        ];
//        $config['ledgerAccount'] = $fen_data;
//        $respont = $this->WeChatPayReady($config);
    }
	public function download(){
        return $this->fetch('share/download');
    }
    //------------------------------------------------------------------------------------------------------------------
    //------------------------------------------------------------------------------------------------------------------
    /**
     * 统一下单
     * @param  array $order 订单 必须包含支付所需要的参数 body(产品描述)、total_fee(订单喵额)、out_trade_no(订单号)、product_id(产品id)、trade_type(类型：JSAPI，NATIVE，APP)
     */
    public function WeChatPayReady($data){
        ksort($data);
        $datastr = $this->arrayToStr($data);
//        $datastr = urldecode($datastr);
        $strSign = $this->createSign($datastr);      //生成签名
        // 生成签名
        $data['sign']=$strSign;
        ksort($data);
        $xml=$this->arrayToStr2($data);
        $url = 'https://mapi.bestpay.com.cn/mapi/aggregatepay/offline/c2b/payOrder';//接收xml数据的文件
        $header[] = "Content-type: application/json";//定义content-type为xml,注意是数组
        $response = https_request($url, $xml, $method = 'POST', $header);
//        dump($response);die;
        $result=json_decode($response,true);
        if($result['errorCode'] == '000000' && $result['errorMsg'] == '成功'){
            $res = [
                'status' => 200,
                'msg' => $result['result']['paymentUrl']
            ];
        }else{
            $res = [
                'status' => 100,
                'msg' => $result['errorMsg']
            ];
        }
        return $res;
    }
    /**
     * 验证
     * @return array 返回数组格式的notify数据
     */
    public function huidiao(){
        // 获取xml
        $xml=json_encode(input());
        $arr = json_decode($xml,true);
        $strSign = $arr['sign'];      //生成签名
        unset($arr['sign']);
        $datastr = $this->arrayToStr($arr);
        $is_ok = $this->verifySign($datastr, $strSign); //验证签名
        if($is_ok){
            //-----------------------------------------------------------------------------
            $num = $arr['outTradeNo'];
            $record = Db::name('record')->where(['record_number'=>$num])->find();
            $shop = Db::name('shop')->where(['shop_id'=>$record['record_shop_id']])->find();
            Db::name('record')
                ->where(['record_id'=>$record['record_id']])
                ->update([
                    'record_third_number' => $arr['tradeNo'],
                    'record_status'=>2,
                    'record_pay_time'=>$arr['tradeFinishedDate'],
                    'record_shop_balance'=>$shop['shop_balance']
                ]);
            if($record['record_ru_id'] > 0){
                Db::name('m_red_user')
                    ->where('ru_id',$record['record_ru_id'])
                    ->update([
                        'ru_status' => 2
                    ]);
            }
            $data = [
                'content' => $arr['tradeNo'] . $xml,
                'time' => date('Y-m-d H:i:s')
            ];
            Db::table('up_z_z_dianxin')->insert($data);
            return  json_encode(["success" => true,"result" => [
                'statusCode' => 200,
                'outTradeNo' => $arr['outTradeNo'],
                'tradeNo' => $arr['tradeNo'],
                'errorCode' => '',
                'errorMsg' => '',
            ]]);
        }
        Db::table('up_z_z_dianxin')->insert(['content' => 'error']);
    }
    /**
     * 获取私钥
     * @return bool|resource
     */
    private static function getPrivateKey()
    {
        $privKey = self::$PRIVATE_KEY;
        return openssl_pkey_get_private($privKey);
    }
    /**
     * 获取公钥
     * @return bool|resource
     */
    private static function getPublicKey()
    {

        $publicKey = self::$PUBLIC_KEY;
        return openssl_pkey_get_public($publicKey);
    }
    /**
     * 创建签名
     * @param string $data 数据
     * @return null|string
     */
    public function createSign($data = '')
    {
        //  var_dump(self::getPrivateKey());die;
        if (!is_string($data)) {
            return null;
        }
        return openssl_sign($data, $sign, self::getPrivateKey(),OPENSSL_ALGO_SHA256 ) ? base64_encode($sign) : null;
    }

    /**
     * 验证签名
     * @param string $data 数据
     * @param string $sign 签名
     * @return bool
     */
    public function verifySign($data = '', $sign = '')
    {
        if (!is_string($sign) || !is_string($sign)) {
            return false;
        }
        return (bool)openssl_verify(
            $data,
            base64_decode($sign),
            self::getPublicKey(),
            OPENSSL_ALGO_SHA1
        );
    }
    /**
     * 数组转字符串
     * @param string $data 数据
     * @param string $sign 签名
     * @return bool
     */
    public function arrayToStr($data)
    {
        $datastr = '';
        foreach ($data as $k=>$v){
            if($v == null) $v = 'null';
            if(is_array($v)) {
                $v = json_encode($v);
            }
            $datastr .= $k . '=' . $v . '&';
        }
        $datastr = trim($datastr,'&');
        return $datastr;
    }
    public function arrayToStr2($data)
    {
        $datastr = '{';
        foreach ($data as $k=>$v){
            if($v == null) $v = 'null';
            if(is_array($v)) {
                $v = json_encode($v);
                $datastr .= '"' . $k . '"' . ':\'' . $v . '\',';
            }else{
                $datastr .= '"' . $k . '"' . ':"' . $v . '",';
            }

        }
        $datastr = trim($datastr,',');
        $datastr .= '}';
        return $datastr;
    }
    //----------------------------------------------------------------------------------------
    public function recordRule($shop_id){
        extract (input());
        $rule = Db::name("record_rule")
            ->where(['rule_shop_id'=>$shop_id])
            ->order('rule_cash ASC')
            ->select();
        //-----
        $conf_rate = Db::name('jifen_conf')->where('conf_id',1)->value ('conf_rate');
        $shop_ratio = DB::name('shop')->where('shop_id',$shop_id)->value('shop_ratio');
        if (!empty($shop_ratio) && !empty($rule)) {
            foreach($rule as $k => $v){
                $ratio = (10-$shop_ratio)/10;
                $rule[$k]['rule_jifen'] = round(($v['rule_cash']*$ratio)/$conf_rate,0);
            }
        }
        //-----
        $data = Db::name('jifen_conf')
            ->where(['conf_id'=>['in','23,24']])
            ->select ();
        $shop_name = Db::name('shop')->where(['shop_id'=>$shop_id])->field('shop_name,shop_img')->find();
        if(empty($shop_ratio)){
            $typetypeee = 1;
            $ratio = 0;
            $ratio2 = 0;
        }else{
            $typetypeee = 2;
            $ratio = (10-$shop_ratio)/10;
            $ratio2 = $shop_ratio;
        }
        return ['shopMsg'=>$rule,'shopMsgJson'=>json_encode($rule),'shopData'=>$data,'shopName'=>$shop_name['shop_name'],'shopImg'=>$shop_name['shop_img'],'shopType'=>$typetypeee,'shopRatio'=>$ratio,'shopRatio2'=>$ratio2,'conf_rate'=>$conf_rate];
    }
    //----------------------------------------------------------------------------------------
    public function addFen($son_mchid){
        $url = "https://api.mch.weixin.qq.com/pay/profitsharingaddreceiver";
        $data["appid"] = $this->config['APPID'];//微信开放平台审核通过的应用APPID
        $data["mch_id"] = $this->config['MCHIDFWS'];//商户号
        $data["sub_mch_id"] = $son_mchid;//
        $data["nonce_str"] = $this->getRandChar(32);//随机字符串
        $data["sign_type"] = 'HMAC-SHA256';
        $data["receiver"] = json_encode([
            'type' => 'MERCHANT_ID',
            'account' => '1603445926',
            'name' => "滁州市爱小屏信息科技有限公司",
            'relation_type' => 'SERVICE_PROVIDER',
        ],JSON_UNESCAPED_UNICODE);
        $sign = $this->makeSign($data,2);
        $data['sign'] = $sign;
        $xml = $this->toXml($data);
        $response = $this->postXmlCurl($xml, $url);
//        dump($response);die;
        $responseArr = $this->toArray($response);
        if (!is_array($responseArr) || count($responseArr) <= 0) {
            $return['msg'] = '网络请求繁忙';
            $return['status'] = 0;
        } else if ($responseArr['return_code'] == 'FAIL') {
            $return['msg'] = $responseArr['return_msg'];
            $return['status'] = 0;
        } else {
            if ($responseArr['result_code'] == 'FAIL') {
                $return['msg'] = $responseArr['err_code_des'];
                $return['status'] = 0;
            } else {
                $return['text'] = $responseArr;
                $return['status'] = 200;
            }
        }
        return $return;
    }
    public function fenMoney(){
        set_time_limit(0);
        $today = date('Y-m-d H:i:s');
        $second_30 = date("Y-m-d H:i:s",(strtotime("{$today}")-30));
        $datas = Db::table('up_record')->alias('r')
            ->join('up_shop_copy sc','r.record_shop_id=sc.sc_shop_id','LEFT')
            ->where('record_status',2)
            ->where('record_fws',2)
            ->where('record_fen',2)
            ->where('record_fen_money','>',0)
            ->where('record_pay_time','<=',$second_30)
            ->page(1,5)
            ->field('record_id,record_number,record_third_number,sc_mch_id,record_sch_id,record_fen_money')
            ->select();
//        dump($datas);die;
        if($datas){
            $url = "https://api.mch.weixin.qq.com/secapi/pay/profitsharing";
            $data["appid"]        = $this->config['APPID'];//微信开放平台审核通过的应用APPID
            $data["mch_id"] 	  = $this->config['MCHIDFWS'];//商户号
            $data["sign_type"] = 'HMAC-SHA256';//随机字符串
            foreach ($datas as $k=>$v){
                $son_mchid = $v['sc_mch_id'];
				if($v['record_sch_id']) $son_mchid = $v['record_sch_id'];
				if($son_mchid == '1603445926'){
                    Db::table('up_record')->where('record_id',$v['record_id'])->setField('record_fen',3);
                }else{
                    $transaction_id = $v['record_third_number'];
                    $refundNo = $v['record_number'];
                    $amount = $v['record_fen_money'];
                    $data["nonce_str"] 	  = $this->getRandChar(32);//随机字符串
                    $data["sub_mch_id"]   = $son_mchid;
                    $data["transaction_id"]   = $transaction_id;
                    $data["out_order_no"]   = $refundNo;
                    $data["receivers"]   = json_encode([[
                        'type' => 'MERCHANT_ID',
                        'account' => '1603445926',
                        'amount' => $amount*100,
                        'description' => '服务商H5扫码支付积分款',
                    ]],JSON_UNESCAPED_UNICODE);
                    $sign=$this->makeSign($data,2);
                    $data['sign']=$sign;
                    $xml=$this->toXml($data);
                    $response 	= $this->postXmlCurl($xml, $url,'',true,ROOT_PATH.'/public/cert/apiclient_cert.pem',ROOT_PATH.'/public/cert/apiclient_key.pem');
                    $responseArr=$this->toArray($response);
//                dump($responseArr);die;
                    if($responseArr['return_code'] == 'SUCCESS' && $responseArr['result_code'] == 'SUCCESS'){
                        Db::table('up_record')->where('record_id',$v['record_id'])->setField('record_fen',3);
                    }
//                    else{
////                        dump($responseArr);die;
//                    }
                }

            }
        }
        exit();
    }
    //--------------------语音播报设备---------------------------
    public function equipment()
    {
        if(!isset($_REQUEST['urlsecretkey']) || !$_REQUEST['urlsecretkey']){
            echo '不合法二维码';
            exit();
        }
        $ss_urlparam = $_REQUEST['urlsecretkey'];
        $data = Db::table('up_shop_ercode')
            ->where('ss_urlparam', $ss_urlparam)
            ->find();
        if(!$data){
            echo '此二维码数据有误！';
            exit();
        }else{
            if($data['ss_shop_id'] <= 0){
                $this->assign('data',$data);
                return $this->fetch('shareh/ercode');
            }else{
                $user_id = Db::table('up_shop')
                    ->where('shop_id', $data['ss_shop_id'])
                    ->value('shop_user_id');
                $user_level = Db::name('u_user')->where('user_id', $user_id)->field('user_invite_code,user_level')->find();
                if ($user_level['user_level'] != 1) {
                    $this->redirect(url('admin/share/register') . '?code=' . $user_level['user_invite_code'] . '&shop_id=' . $data['ss_shop_id']);
                } else {
                    $this->redirect(url('admin/share/register') . '?code=&shop_id=' . $data['ss_shop_id']);
                }
            }
        }
    }
    public function bindShopCode()
    {
        extract(input());
        if ($code == '') {
            return json(['status' => 100, 'msg' => '请填写验证码']);
        }
        $phone_code = Db::name('phonecode')->where(['phone' => $phone, 'status' => 0, 'type' => 1])->find();
        if (empty($phone_code)) {
            return json(['status' => 100, 'msg' => '请先发送验证码']);
        }
        $diff = time() - $phone_code['time'];
        if ($diff >= 30 * 60) {
            return json(['status' => 100, 'msg' => '验证码已失效']);
        }
        if ($code != $phone_code['code']) {
            return json(['status' => 100, 'msg' => '验证码输入错误']);
        }
        $shop = Db::table('up_shop')
            ->where('shop_account', $phone)
            ->field('shop_id,shop_attestation,shop_status')
            ->find();
        if (!$shop) return json(['status' => 100, 'msg' => '您还不是商家']);
        if ($shop['shop_attestation'] != 2) return json(['status' => 100, 'msg' => '只有认证通过的商家才可以绑定']);
        if ($shop['shop_status'] != 1) return json(['status' => 100, 'msg' => '此账号已被冻结，请联系管理员']);
        $have = Db::table('up_shop_ercode')
            ->where('ss_shop_id', $shop['shop_id'])
            ->find();
        if ($have) return json(['status' => 100, 'msg' => '此商家已经绑定过设备了']);
        $ss_about_name = strtoupper($ss_about_name);
        $have = Db::table('up_shop_ercode')
            ->where('ss_about_name', $ss_about_name)
            ->find();
        if ($have) return json(['status' => 100, 'msg' => '此设备已经绑定商家了']);
        $have = Db::table('up_shop_ercode')
            ->where('ss_uni_name', $ss_about_name)
            ->find();
        if (!$have) return json(['status' => 100, 'msg' => '无此设备，请检查好填写']);
        $res = Db::table('up_shop_ercode')
            ->where('ss_urlparam', $ss_urlparam)
            ->update([
                'ss_shop_id' => $shop['shop_id'],
                'ss_about_name' => $ss_about_name,
                'ss_bindtime' => date('Y-m-d H:i:s')
            ]);
        if ($res) {
            Db::name('phonecode')->where(['phone' => $phone, 'status' => 0, 'type' => 1])->setField('status',1);
            return json(['status' => 200, 'msg' => '绑定成功']);
        } else {
            return json(['status' => 100, 'msg' => '绑定失败']);
        }
    }
    //-------------------------------------------------------------------------------------------------
    //------------------专为达标统计用的----------------------------------------------
    //-------------------------------------------------------------------------------------------------
    public function tjDoneAdmin()
    {
        set_time_limit(0);
        $datas = Db::name('record')
            ->where('record_status',2)
            ->where('record_type','<>',2)
            ->where('record_pay_month',null)
            ->field('record_id,record_pay_time')
            ->select ();
        foreach ($datas as $k => $v){
            $month = substr($v['record_pay_time'],0,7);
            Db::name('record')->where('record_id',$v['record_id'])->setField('record_pay_month',$month);
        }
        //-----------------------------------------------------------------
        $lists = Db::name('record r')
            ->join("up_shop_ercode sc",'r.record_shop_id = sc.ss_shop_id','left')
            ->where('record_status',2)
            ->where('record_type','<>',2)
            ->where('record_pay_month_status',1)
            ->group('record_shop_id,record_pay_month')
            ->field('r.*,sc.ss_shop_id,sc.ss_bindtime')
            ->order('record_add_time DESC')
            ->select ();
//        dump($lists);die;
        if($lists){
            foreach ($lists as $k => $v){
                $nums = 0;
                $users = 0;
                if($v['ss_bindtime']){
                    $users = Db::name('record')
                        ->where('record_status',2)
                        ->where('record_type','<>',2)
                        ->where('record_money','>=',5)
                        ->where('record_add_time','>=',$v['ss_bindtime'])
                        ->where('record_pay_month',$v['record_pay_month'])
                        ->where('record_shop_id',$v['record_shop_id'])
                        ->group('record_user_id')
                        ->count();
                    $nums = Db::name('record')
                        ->where('record_status',2)
                        ->where('record_type','<>',2)
                        ->where('record_pay_month',$v['record_pay_month'])
                        ->where('record_shop_id',$v['record_shop_id'])
                        ->count();
                }

                $update = [
                    'record_pay_month_status' => 2
                ];
                if($users >= 20 && $nums >= 100) {
                    $update['record_pay_month_done'] = 2;
                };
                Db::name('record')
                    ->where('record_status',2)
                    ->where('record_type','<>',2)
                    ->where('record_pay_month',$v['record_pay_month'])
                    ->where('record_shop_id',$v['record_shop_id'])
                    ->update($update);
            }
        }
        exit();
    }
}